<template>
  <div class="login">
    <div class="title" style="font-size: 40px;">欢迎登录</div>
      <van-form>
        <van-field
          v-model = "username"
          name = "用户名"
          label = "用户名"
          placeholder = "用户名"
          sise = "large"
          :rules = "[{ required: true,message:'请填写用户名'}]"
        />
        <van-field
          v-model = "password"
          type = "password"
          name = "密码"
          label = "密码"
          placeholder = "密码"
          sise = "large"
          :rules = "[{ required: true,message:'请填写密码'},
                       {validator:validatePassword,message:'密码长度至少为6位'}]"
        />
        <div style="margin-top: 16px;">
           <van-button round block type="primary" @click="onSubmit">登录</van-button>
        </div>
        <div class="footer" style="font-size: 20px;">
          没有账号，<span class="register" @click="goRegister">去注册</span>
        </div>
      </van-form>
  </div>
</template>

<script>
import { ref, getCurrentInstance} from 'vue';
import router from '../router/index'
import { onMounted } from 'vue';

export default{
  setup(){
    const {proxy} = getCurrentInstance()
    const username = ref('');
    const password = ref('');
    let loginInfo;
    const validatePassword = (val) => /\d{6}/.test(val);

    const onSubmit = async () => {
      let data = {username:username.value,password:password.value}
      loginInfo = await proxy.$axios.post('/login',data)

      if (username.value != loginInfo.username ||
          password.value != loginInfo.password+''){
            proxy.$toast.fail('用户名和密码错误...');
          }else{
            localStorage.setItem('isLogin',JSON.stringify(true))
            localStorage.setItem('user',username.value)
            proxy.$toast.success('登录成功')
            router.push('/home')
          }
    }

    const goRegister = () => {
      router.push('/register')
    }
    onMounted(() =>{});
    return{
      username,
      password,
      validatePassword,
      onSubmit,
      goRegister
    }


  }
}

</script>

<style scoped>
.login{
  display:flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #eee;
  height: 100%;
}
.title{
  font-size: 1.75rem;
}
.van-form{
  height: 18.75rem;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.van-cell--large{
  margin: 0.625rem 0;
  border-radius: 0.5rem;
}
.footer{
  color: #ccc;
  text-align: center;
  font-size: 0.875rem;
  padding:0.625rem,0;
}
.register{
  color: #aaa;
  font-weight: bold;
}

</style>
